<template>
  <el-dialog
    ref="selectAgent2"
    title="选择机器"
    width="400px"
    :close-on-click-modal="false"
    :visible.sync="params.visible"
  >
    <el-tabs v-model="activeTab" type="border-card">
      <el-tab-pane label="资源池" name="Robot">
        <compTreeTable
          ref="xTree1"
          :show-checkbox="inParams.checkbox"
          :show-icon="true"
          icon-prop="text"
          :table-height="350"
          :table-data="tableData1"
          :table-header="tableHeader1"
          :check-column-method="checkColumnMethod"
        />
      </el-tab-pane>
      <el-tab-pane v-if="isShowRobotParam" label="机器参数" name="RobotParam">
        <compTreeTable
          ref="xTree2"
          :show-checkbox="inParams.checkbox"
          :show-icon="true"
          icon-prop="name"
          :table-height="350"
          :table-data="tableData2"
          :table-header="tableHeader2"
        />
      </el-tab-pane>
    </el-tabs>
    <dialog-btn slot="footer">
      <el-checkbox
        v-show="activeTab === 'Robot'"
        v-model="isSelectGroup"
        style="float: left"
        @change="onAgentGroup"
      >选择分组</el-checkbox>
    </dialog-btn>
  </el-dialog>
</template>

<script>
/**
 * 原 dialogs/select_agent.html页面
 */
import { ParamArr, SQLTable } from '@/../public/js/paramarr'
import Global from '../../../public/js/global'
import { getAgentListByCore } from '@/api/core'
export default {
  name: 'SelectAgent2',
  props: {
    params: {
      type: Object,
      default: () => {
        return {
          visible: false,
          ids: '', // 选中的id
          isIPs: false, // 是否时ip
          checkbox: true, // 是否多选
          notParam: true, // 是否显示机器参数
          notGroup: true // 是否可以选择分组
        }
      }
    }
  },
  data() {
    return {
      inParams: {}, // 接收入参
      activeTab: 'Robot',
      tableData1: [],
      tableHeader1: [
        { prop: 'text', label: '机器' },
        {
          prop: 'isFolder',
          label: '目录',
          align: 'center',
          width: 50,
          render: (h, { row }) => {
            if (row.folder) {
              return (
                <vxe-checkbox
                  value={row.checkGroup}
                  onChange={(check) => {
                    row.checkGroup = check.checked
                  }}
                />
              )
            }
          }
        }
      ],
      tableData2: [],
      tableHeader2: [
        { prop: 'name', label: '参数' },
        { prop: 'ip', label: 'IP' }
      ],
      isSelectGroup: false, // 资源池-是否选择分组
      isShowRobotParam: true // 是否显示机器参数
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      this.inParams = this.params
      // 初始化入参
      this.inParams.ids = this.inParams.ids || ''
      this.inParams.isIPs =
        this.inParams.isIPs === undefined ? false : this.inParams.isIp
      this.inParams.checkbox =
        this.inParams.checkbox === undefined ? true : this.inParams.checkbox
      this.inParams.notParam =
        this.inParams.notParam === undefined ? true : this.inParams.notParam
      this.inParams.notGroup =
        this.inParams.notGroup === undefined ? true : this.inParams.notGroup
      // 初始化资源池选择分组复选框
      if (this.inParams.notGroup) {
        if (this.parseParams(this.inParams.ids, 0) === 'RobotGroup') {
          this.isSelectGroup = true
        }
      }
      // 初始化标签页
      this.activeTab =
        this.parseParams(this.inParams.ids, 0) === 'RobotParam'
          ? 'RobotParam'
          : 'Robot'
      const vPar = new ParamArr()
      vPar.setBool('IsAgentParam', true)
      getAgentListByCore(vPar)
        .then((vPar) => {
          // 初始化资源池数据
          this.initAgentList(vPar)
          if (!this.inParams.notParam) {
            this.isShowRobotParam = false
          } else {
            // 初始化机器参数数据
            this.initAgentParamList(vPar)
          }
        })
    },
    // 初始化资源池数据
    initAgentList(vPar) {
      const nodes = []
      const table = new SQLTable(vPar.getTable('k_group'))
      table.first()
      while (!table.eof()) {
        const node = {}
        node['id'] = table.getValueByName('ID')
        node['pid'] = table.getValueByName('PID')
        node['name'] = table.getValueByName('Name')
        node['text'] = node.name
        node['icon'] = 'wenjianyi'
        node['checkGroup'] =
          this.parseParams(this.inParams.ids, 1).indexOf(node.id) !== -1
        // node['tags'] = [strFormat('<input type="checkbox" {0}>', node.checkGroup ? 'checked' : '')]
        node['folder'] = true
        nodes.push(node)
        table.next()
      }
      this.getAgentData(
        new SQLTable(vPar.getTable('k_computer')),
        false,
        nodes
      )
      this.getAgentData(
        new SQLTable(vPar.getTable('k_computer_map')),
        true,
        nodes
      )
      this.tableData1 = nodes
      // 初始化目录列
      if (this.isSelectGroup) {
        this.$refs.xTree1.showColumn('isFolder')
      } else {
        this.$refs.xTree1.hideColumn('isFolder')
      }
    },
    getAgentData(table, isMap, nodes) {
      const maps = this.parseParams(this.inParams.ids, 2) || ''
      table.first()
      while (!table.eof()) {
        const node = {}
        node['id'] = table.getValueByName('ID')
        node['ip'] = table.getValueByName('IP')
        node['name'] = table.getValueByName('Name')
        node['pid'] = table.getValueByName('GroupID')
        node['system'] = table.getValueByName('System')
        node['online'] = table.getValueByName('Online')
        node['mapId'] = table.getValueByName('MapID') || ''
        // node['tags'] = ['<input type="checkbox" disabled>']
        node['agentName'] = table.getValueByName('AgentName')
        node['agent'] = node.ip + '[' + node.name + ']'

        node['text'] = node.agent
        node['icon'] = Global.getSystemIconStr(node.system)
        if (isMap) node['color'] = '#5555ff' // 是否为映射机器
        if (node.online === '0') node['color'] = '#b4b4b4' // 机器是否在线
        // 是否勾选
        node['checked'] = false
        if (isMap) {
          node['checked'] =
            maps.indexOf(Global.MD5(node.mapId + node.ip)) !== -1 ||
            maps.indexOf(node.mapId + node.ip) !== -1
        } else {
          node['checked'] =
            maps.indexOf(Global.MD5(node.ip)) !== -1 ||
            maps.indexOf(Global.MD5(node.id)) !== -1 ||
            (',' + maps + ',').indexOf(',' + node.ip + ',') !== -1
        }
        if (node.checked) this.$refs.xTree1.setCheckboxRow(node, true)
        nodes.push(node)
        table.next()
      }
    },
    // 初始化机器参数数据
    initAgentParamList(vPar) {
      const maps = this.parseParams(this.inParams.ids, 1) || ''
      const nodes = []
      let table = new SQLTable(vPar.getTable('k_agent_param_group'))
      table.first()
      while (!table.eof()) {
        const node = {}
        node['id'] = table.getValueByName('ID')
        node['pid'] = table.getValueByName('PID')
        node['name'] = table.getValueByName('Name')
        node['text'] = node.name
        node['icon'] = 'wenjianyi'
        node['folder'] = true
        nodes.push(node)
        table.next()
      }
      table = new SQLTable(vPar.getTable('k_agent_param'))
      table.first()
      while (!table.eof()) {
        const node = {}
        node['id'] = table.getValueByName('ID')
        node['ip'] = table.getValueByName('IP')
        node['pid'] = table.getValueByName('PID')
        node['name'] = table.getValueByName('Name')
        node['text'] = node.name
        node['icon'] = 'shuxing'
        node['folder'] = false
        node['tags'] = [node.ip]
        node['checked'] =
          maps.indexOf(node.id) !== -1 ||
          (',' + maps + ',').indexOf(',' + node.name + ',') !== -1
        if (node.checked) this.$refs.xTree2.setCheckboxRow(node, true)
        nodes.push(node)
        table.next()
      }
      this.tableData2 = nodes
    },
    parseParams(str, index) {
      if (!str) return ''
      str = str.replace(/}{/g, '-')
      str = str.replace(/[}{]/g, '')
      return str.split('-')[index] || ''
    },
    onAgentGroup() {
      if (this.isSelectGroup) {
        this.$refs.xTree1.showColumn('isFolder') // 显示目录列
        return false // 复选框全部禁止选中
      } else {
        this.$refs.xTree1.hideColumn('isFolder') // 隐藏目录列
        return true // 复选框全部可选
      }
    },
    checkColumnMethod() {
      if (this.isSelectGroup) {
        return false // 复选框全部禁止选中
      } else {
        return true // 复选框全部可选
      }
    },
    confirm() {
      const ids = []
      let names = []
      const mapIDs = []
      let str = ''
      if (this.activeTab === 'RobotParam') {
        const nodes = this.$refs.xTree2.getCheckboxRecords(true)
        for (let i = 0; i < nodes.length; i++) {
          if (!nodes[i].folder) {
            ids.push(nodes[i].id)
            names.push(nodes[i].name)
          }
        }
        if (ids.length === 0) return this.$message.warning('请选择机器参数')
        if (names.length > 3) names = [names.length + '个机器参数']
        str = `{RobotParam}{${ids.join(',')}}`
      }

      if (this.activeTab === 'Robot') {
        if (this.isSelectGroup) {
          for (const node of this.tableData1) {
            if (node.folder && node.checkGroup) {
              ids.push(node.id)
              names.push(node.name)
            }
          }
          if (ids.length === 0) return this.$message.warning('请选择分组')
          str = `{RobotGroup}{${ids.join(',')}}`
        } else {
          if (!this.inParams.checkbox) {
            // 单选
            const node = this.$refs.xTree1.getCurrentRecord()
            if (!node.folder) {
              ids.push(node.id)
              names.push(`${node.ip} [${node.name}]`)
              mapIDs.push(Global.MD5(node.mapId + node.ip))
            }
          } else {
            // 多选
            const nodes = this.$refs.xTree1.getCheckboxRecords()
            for (const node of nodes) {
              if (!node.folder) {
                ids.push(node.id)
                names.push(`${node.ip} [${node.name}]`)
                mapIDs.push(Global.MD5(node.mapId + node.ip))
              }
            }
          }
          if (ids.length === 0) return this.$message.warning('请选择机器')
          if (names.length > 3) names = [names.length + '个机器']
          str = `{Robot}{${ids.join(',')}}{${mapIDs.join(',')}}`
        }
      }
      const params = {
        ids: str,
        name: names.join(',')
      }
      if (this.params.confirm !== undefined) {
        this.params.confirm(params)
      } else {
        this.$emit('confirm', params)
      }
    }
  }
}
</script>

<style scoped>
</style>
